//使用vite懒加载
const Module = import.meta.glob("@/views/**/*.vue")
import router from "@/router/index";
import axios from "@/assets/common/request"

//懒加载组件
function loadComponent(url){
    let path = Module[`/src/views/${url}.vue`];
    return path
}
const getDynamicRoute = (menuTree,routes) =>{
    if(!routes){
        routes = []
    }
    menuTree.forEach((menu)=>{
        if(menu.path && menu.path.startsWith('/') && menu.component){
            let _index = routes.findIndex(r=>r.path === menu.path);
            if(_index !== -1){
                //该路径已添加过
                routes[_index].meta.title = menu.title;
                return;
            }
            // console.log(menu.component);
            let routeItem = {
                path: menu.path,
                // name: "Home",
                meta: {
                    title: menu.menuName,
                },
                component: loadComponent(menu.component)
            };
            routes.push(routeItem);
        }
        if(menu.children && menu.children.length>0){
            getDynamicRoute(menu.children,routes)
        }
    })
    return routes
}
const addDynamicRoute = async (menuTree) =>{
    // console.log(router.getRoutes());
    if(!menuTree){
        try {
            if(localStorage.getItem("token") && localStorage.getItem("bases")){
                // let res = await axios('/menus/treeSelect');
                // menuTree = res.data.data;
                // localStorage.setItem("menuTree", JSON.stringify(menuTree))
                let bases = JSON.parse(localStorage.getItem("bases"));
                menuTree = bases.menuTree;
                // console.log(menuTree);
            }
        }catch(error){
            menuTree = []
        }
    }
    let dynamicRoutes = getDynamicRoute(menuTree||[]);
    // console.log(dynamicRoutes);
    // console.log(menuTree);
    dynamicRoutes.forEach(item => {
        router.addRoute(item)
    })
}

export default addDynamicRoute